#include "unmanedsupermarketsys.h"
#include "ui_unmanedsupermarketsys.h"
#include <main.h>
extern QSettings settings;
extern bool state_fullscreen;
//#include <QTimer>
unmanedsupermarketsys::unmanedsupermarketsys(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::unmanedsupermarketsys)
{
    setting *sss = new setting;
    ui->setupUi(this);
//  ==================ui=========================
    //不用系统渲染
    setWindowFlag(Qt::FramelessWindowHint);
    // 设置窗口透明度
    setWindowOpacity(opacity);
    connect(sss, &setting::windowClosed, this, &unmanedsupermarketsys::onWindowClosed);
    // 设置窗口样式表
//        setStyleSheet("background-color: rgba(0, 0, 0, 128); border-radius: 10px; color:rgb(255,255,255);");
    setStyleSheet("background-color: rgba(128, 128, 128, 128); border-radius: 10px; color:rgb(0,0,0);");
    setStyleSheet("background-color: rgba(220,220,220, 128); border-radius: 10px; color:rgb(0,0,0);");
    //    ui->label->setObjectName("label");
    //    ui->label_2->setObjectName("label");
    //    ui->label_3->setObjectName("label");
    //    QList<QLabel*> lablist = this->findChildren<QLabel*>("label");

//==================timer========================
    dateTime = QDateTime::currentDateTime();//init
    ui->labeltimer->setText(dateTime.toString("yyyy-MM-dd hh:mm:ss ddd"));

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &unmanedsupermarketsys::timeUpdate);
    timer->start(1000);
//=================tcp server=====================
//    QHostAddress localIP = QHostAddress("30.252.22.10");
    tcpServer = new QTcpServer(this);
    QHostAddress ip = QHostAddress::LocalHost;
    QList<QHostAddress> addrList = QNetworkInterface::allAddresses();
    for (int i = 0; i < addrList.size(); i++)
    {
        QHostAddress address = addrList.at(i);
        if (address.protocol() == QAbstractSocket::IPv4Protocol && !address.isNull())
        {
            ip = address;
            break;
        }
    }
//    QHostAddress ip = QHostAddress::AnyIPv4;
    quint16 port = 0503;

//    tcpSocket->abort();
//    if(tcpSocket->bind(localIP,42005))
//    {
//    qDebug() << "1 LocalHost:" << localIP.toString();
//    qDebug() << "2 localPort:" << tcpSocket->localPort();
//}
//    tcpSocket->connectToHost(QHostAddress::LocalHost,port);
//    tcpServer->connect(ip,port);
//    ==============================listen=======================
    bool state = tcpServer->listen(ip,port);

//    tcpServer = new QTcpServer(this);
//    bool state = tcpServer -> listen(QHostAddress(ip),port);
//    if(state){
////            qDebug()<<"正在TCP Server模式...";
//        QMessageBox::information(this,
//            tr("正在TCP Server模式..."),
//             tr(
//                "正在TCP Server模式...\n")
//                );
//    }else{
//        QString error  = QString("[%1,%2]\n").arg(ip.toString()).arg(port);

//        QMessageBox::critical(this,
//            tr("启动失败！！！"),
//            tr(error.toUtf8()));
////        qDebug()<<"启动失败";
//    }
//    tcpSocket->connectToHost(ip,port);
//    tcpSocket = tcpServer  -> nextPendingConnection();//取出套接字
    //    QString localHostName = QHostInfo::localHostName();
    connect(tcpServer,&QTcpServer::newConnection,this,&unmanedsupermarketsys::connectSucceed);
    ui->lineEdit ->setText(QString("%1:%2").arg(ip.toString()).arg(port));
//    connect(tcpServer,&QTcpServer::newConnection,this,&unmanedsupermarketsys::connectSucceed);
//=======================display data============
////=======================@copyright================
///====================CWNU_SE_2021_CYS==============
//    connect(btn,SIGNAL(clicked()),this,SLOT(reject()));
//=========================menu btn connect==============
    QAction *myAction  =  this->findChild<QAction*>("action");
    connect(myAction,&QAction::triggered, [=]() {
        // 打开文件
//        qDebug() << "Menu item clicked!";

       QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::homePath(), tr("All Files (*.*)"));
       if (!fileName.isEmpty()) {
               // 用户选择了文件
               qDebug() << "已选择文件：" << fileName;
               QSettings setting2(fileName,QSettings::IniFormat);
               qDebug()<<"=====================================setttings-================================== ";
               setting2.beginGroup("client");
               settings.beginGroup("client");
               settings.setValue("username",setting2.value("username", "defaultUsername").toString());
               settings.setValue("password",setting2.value("password", "defaultPassword").toString());
               settings.setValue("state",setting2.value("state", 0).toInt());
               qDebug()<<setting2.value("username", "defaultUsername").toString()
                      <<setting2.value("password", "defaultPassword").toString()
                     <<setting2.value("state",0).toInt();
               settings.endGroup();
               setting2.endGroup();
               setting2.beginGroup("server");
               settings.beginGroup("server");
               settings.setValue("username",setting2.value("username", "defaultUsername").toString());
               settings.setValue("password",setting2.value("password", "defaultPassword").toString());
               settings.setValue("state",setting2.value("state", 0).toInt());
               qDebug()<<setting2.value("username", "defaultUsername").toString()
                      <<setting2.value("password", "defaultPassword").toString()
                     <<setting2.value("state",0).toInt();
               settings.endGroup();
               setting2.endGroup();

               settings.sync();

//               settings.beginGroup("server");
//               QString username = settings.value("username", "defaultUsername").toString();
//               QString password = settings.value("password", "defaultPassword").toString();
//               int state = settings.value("state", 0).toInt();
//               qDebug()<<username<<password<<state;
//               settings.endGroup();

//               settings.beginGroup("client");
//               username = settings.value("username", "defaultUsername").toString();
//               password = settings.value("password", "defaultPassword").toString();
//               state = settings.value("state", 0).toInt();
//               qDebug()<<username<<password<<state;
//               settings.endGroup();

           } else {
               // 用户取消选择或未选择文件
               qDebug() << "未选择文件夹";

           }
//       settings = new QSettings(fileName, QSettings::IniFormat);

//       QStringList username2;
//       QStringList password2;
//       QList<int> state2;
//       setting2.beginGroup("server");
//       QString username = setting2.value("username", "defaultUsername").toString();
//       QString password = setting2.value("password", "defaultPassword").toString();
//       int state = setting2.value("state", 0).toInt();
//       setting2.endGroup();


//       setting2.beginGroup("client");
//       username = setting2.value("username", "defaultUsername").toString();
//       password = setting2.value("password", "defaultPassword").toString();
//       state = setting2.value("state", 0).toInt();
//       setting2.endGroup();
//===================update ini===============================

    });

    QAction *myAction2  =  this->findChild<QAction*>("action_2");
    connect(myAction2, &QAction::triggered, [=]() {
        // 在这里执行操作
////        qDebug() << "Menu item clicked!";
//        QMessageBox::information(this,
//                tr("懒得做了 将就吧"),
//             tr(
//                "Copyright © [2023]- [CWNU_SE_2021_CYS]. All rights reserved.\n"
//                "Copyright © [2023]- [CWNU_SE_2021_CYS]。保留所有权利。\n")
//                );

        sss->show();

    });
    QAction *myAction3  =  this->findChild<QAction*>("action_3");
    connect(myAction3, &QAction::triggered, [=]() {
        // 在这里执行操作
//        qDebug() << "Menu item clicked!";
        QMessageBox::information(this,
                tr("CodeBY CWNU_SE_2021_CYS\n"),
             tr(
                "Copyright © [2023]- [CWNU_SE_2021_CYS]. All rights reserved.\n"
                "Copyright © [2023]- [CWNU_SE_2021_CYS]。保留所有权利。\n")
                );
    });
//=============menubar 's exit is written=============
    QAction *myAction4  =  this->findChild<QAction*>("action_4");
    connect(myAction4, &QAction::triggered, [=]() {
        // 在这里执行操作
//        qDebug() << "Menu item clicked!";
        QMessageBox::information(this,
        tr("无人超市水果采集系统"
           ),
        tr("欢迎下次使用\n""再见...\n")
        );
    });
}

unmanedsupermarketsys::~unmanedsupermarketsys()
{
    delete ui;
}
void unmanedsupermarketsys::startup(){
//    QLabel *label = new QLabel(&m)

//        QLabel *label = ui->pic;
//        QPixmap pix("./image/apple.jpg");
//        QPixmap dest = pix.scaled(ui->pic->size(),Qt::KeepAspectRatio);
//        ui->pic ->setPixmap(dest);

// =================================TCP Server=====================

//    if(ui->connectbtn->text()=="连接"){
//    QString host_addr = ui->addrline->text();
//    quint16 host_port = ui->portline->text().toUShort();

//    qDebug()<<tcpServer;
//    qDebug()<<tcpServer<<state;

//
//        ui->typebox ->setEnabled(false);
//        ui->addrline->setEnabled(false);
//        ui->portline ->setEnabled(false);
//        ui->connectbtn->setText("断开");
        qDebug()<<"正在监听端口...";

//        connect(tcpServer,&QTcpServer::newConnection,this,&unmanedsupermarketsys::connectSucceed);


//        connect(tcpSocket
//                ,&QTcpSocket::connected
//                ,this,&unmanedsupermarketsys::Server_connectSucceed);
//        connect(tcpSocket
//                ,&QTcpSocket::readyRead
//                ,this
//                ,&unmanedsupermarketsys::read_ServerData);
//    }else{
//        qDebug()<<"启动服务器失败";
//        ui->typebox ->setEnabled(true);
//        ui->addrline->setEnabled(true);
//        ui->portline ->setEnabled(true);
//        ui->connectbtn->setText("连接");
//    }

}
void unmanedsupermarketsys::read_ServerData(){
//    QString recv_data = QString(tcpSocket->readAll()).toUtf8();
//    recv_data = recv_data.replace("{","");
//    recv_data = recv_data.replace("}","");
//    QArrayData data = recv_data.split(",");
//    QString display =QString("单价：%1元/Kg\n重量：%2\n当前时间：%3\b").arg(data[2]).arg(data[3]).arg(dateTime.toString("yyyy-MM-dd hh:mm:ss ddd"));
//    ui->textEdit->setText(display);

}

void unmanedsupermarketsys::Server_connectSucceed(){
//    tcpSocket = tcpServer  -> nextPendingConnection();//取出套接字
//    QString  ip = tcpSocket ->peerAddress().toString();
//    unsigned short port = tcpSocket->peerPort();
//    ui->lineEdit_2 ->setText(QString("[%1:%2]").arg(ip).arg(port);
//    connect(tcpSocket,&QTcpSocket::readyRead,this,&socket::recv_client_Data);
//    connect(tcpSocket,&QTcpSocket::disconnected,this,&socket::disConnect);
}
void unmanedsupermarketsys::timeUpdate(void)
{
    dateTime = QDateTime::currentDateTime();
    ui->labeltimer->setText(dateTime.toString("yyyy-MM-dd ddd hh:mm:ss "));
}
void unmanedsupermarketsys::connectSucceed(){
    tcpSocket = tcpServer  -> nextPendingConnection();//取出套接字
    QString  ip = tcpSocket ->peerAddress().toString();
    unsigned short port = tcpSocket->peerPort();
    qDebug()<<QString("[%1,%2],成功连接...\n").arg(ip).arg(port);
    ui->lineEdit_2->setText(QString("%1:%2").arg(ip).arg(port));
    QMessageBox::information(this,
            tr("已连接客户端..."),tr("已连接客户端...")
            );

    connect(tcpSocket,&QTcpSocket::readyRead,this,&unmanedsupermarketsys::recv_client_Data);
    connect(tcpSocket,&QTcpSocket::disconnected,this,&unmanedsupermarketsys::disConnect);
}
void unmanedsupermarketsys::recv_client_Data(){
    QString recv_data = QString(tcpSocket->readAll()).toUtf8();
//    qDebug()<<recv_data;
//    recv_data = recv_data.replace("{","");
//    recv_data = recv_data.replace("}","");
    QString data = recv_data.replace("{","");
    data = data.replace("}","");
//    qDebug()<<data;
    QStringList datas = data.split(",");

    //小心数组越界
//    QString pic_src = QString("://home/image/fruit/%1.jpg").arg(datas[0]);
//    qDebug()<<pic;
//    QImage *img = new QImage;
//    img->load(pic_src);
//    qDebug()<<pic_src;
//    ui->pic->setPixmap(QPixmap::fromImage(*img));
//    ui->pic->setScaledContents(true);
//    QString display = QString("单价：%1/元\n重量：%2/Kg\n当前时间：%3\b").arg(datas[1]).arg(datas[2]).arg(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
//    qDebug()<<display;
//    ui->textEdit->setText(display);

//    QVector<QString> srcs;
//    QVector<QString> prices;
//    QVector<QString> weigths;
//    QVector<QString> times;
    int i = 0;
    for(i = 0  ; i < srcs.size() ; ++ i ){
        if(datas[0] == srcs[i]){
            srcs[i] = datas[0];
            prices[i] =datas[1];
            weigths[i] = datas[2];
            times[i] = dateTime.toString("yyyy-MM-dd hh:mm:ss");
            qDebug()<<srcs[i]<<datas[0]<<datas[1]<<datas[2];
            break;
//            i--;
        }
    }
    QFile file(QString("://home/image/fruit/%1.jpg").arg(datas[0]));
    if( i == srcs.size()){
        if(!file.exists()){
            QMessageBox::critical(this,
                    tr("你这是啥水果..."),QString("没有 %1 水果的图片").arg(datas[0])
                    );
            return ;
        }
        srcs.append(datas[0]);
        prices.append(datas[1]);
        weigths.append(datas[2]);
        times.append(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
    }

    //================================建立组件列表方便遍历
            ui->pic->setObjectName("piclab");
            ui->pic_2->setObjectName("piclab");
            ui->pic_3->setObjectName("piclab");
            ui->pic_4->setObjectName("piclab");
            ui->pic_5->setObjectName("piclab");
            ui->pic_6->setObjectName("piclab");
            QList<QLabel*> piclist = this->findChildren<QLabel*>("piclab");

            ui->textEdit->setObjectName("textEditmsg");
            ui->textEdit_2->setObjectName("textEditmsg");
            ui->textEdit_3->setObjectName("textEditmsg");
            ui->textEdit_4->setObjectName("textEditmsg");
            ui->textEdit_5->setObjectName("textEditmsg");
            ui->textEdit_6->setObjectName("textEditmsg");
            QList<QTextEdit*> tdlist = this->findChildren<QTextEdit*>("textEditmsg");
//            for(int i = 0 ; i < 6 ; ++i){
//                // 动态显示 砍掉了
//                if(ishide[i] == 0){
//                    piclist.at(i)->hide();
//                    tdlist.at(i)->hide();
//                }else {
//                    piclist.at(i)->show();
//                    tdlist.at(i)->show();
//                }
//            }


    for (int j = 0; j < times.size() ;++j) {
//        QString comp_pic_name;
//        QString comp_textEdit_name;
//        if(j == 1){
//            comp_pic_name = QString("pic");
//            comp_textEdit_name = QString("textEdit");
//        }else {
//            comp_pic_name = QString("pic_%1").arg(j);
//            comp_textEdit_name = QString("textEdit_%1").arg(j);
//        }

//        QLabel *comp_pic = this->findChild<QLabel*>(comp_pic_name);
//        QLabel *comp_textEdit = this->findChild<QLabel*>(comp_textEdit_name);
        QImage *img = new QImage;
        img->load(QString("://home/image/fruit/%1.jpg").arg(srcs[j]));
//        comp_pic->setPixmap(QPixmap::fromImage(*img));
//        comp_pic->setScaledContents(true);
        QLabel *piclab  = piclist.at(i);
        QTextEdit *tdmsg = tdlist.at(i);
//        ishide[i] = 1;

        piclab->setPixmap(QPixmap::fromImage(*img));
        piclab->setScaledContents(true);
        QString display = QString("单价：%1\\元\n重量：%2\\Kg\n当前时间：\n%3").arg(prices[j])
                .arg(weigths[j])
                .arg(times[j]);
//        qDebug()<<display;
//        qDebug()<<srcs[j];

        tdmsg->setText(display);
//        comp_textEdit->setText(display);
    }


}


void unmanedsupermarketsys::disConnect(){
    QString str_disconnect ="客户端主动断开连接...";
    QMessageBox::critical(this,
            tr("客户端主动断开连接..."),tr("客户端主动断开连接...")
            );
    ui->lineEdit_2->setText(QString("未连接"));
}
void unmanedsupermarketsys::mousePressEvent(QMouseEvent *event)
{
    m_dragging = true;
    m_lastPos = event->globalPos() - frameGeometry().topLeft();
}

void unmanedsupermarketsys::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging)
    {
        QPoint newPos = event->globalPos() - m_lastPos;
        move(newPos);
    }
}

void unmanedsupermarketsys::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    m_dragging = false;
}
void unmanedsupermarketsys::onWindowClosed()
{

//          QMessageBox::information(this, "Notification", "Main window is closed.");
         setWindowOpacity(opacity);
         if(state_fullscreen){
            setWindowState(Qt::WindowFullScreen);
         }else{
//                setWindowState(Qt::WindowFullScreen);

              // 获取屏幕的宽度和高度
              QScreen *screen = QGuiApplication::primaryScreen();
              QRect screenGeometry = screen->geometry();
              int screenWidth = screenGeometry.width();
              int screenHeight = screenGeometry.height();

              // 设置窗口的大小为屏幕宽度和高度的60%
              int windowWidth = screenWidth * 0.6;
              int windowHeight = screenHeight * 0.6;
              setGeometry((screenWidth - windowWidth) / 2, (screenHeight - windowHeight) / 2, windowWidth, windowHeight);

         }

};
